package com.study.algorithm.search;

public class BinarySearch {
    public static int binarySearch(int[] nums, int target) {
        int low = 0;
        int high = nums.length - 1;
        //如果小于最小值或者大于最大值则没有结果
        if (target < nums[low] || target > nums[high]) {
            return -1;
        }
        while (low <= high) {
            int middle = (high + low) / 2;
            if (nums[middle] == target) {
                return middle;
            } else if (nums[middle] > target) {
                high = middle - 1;
            } else {
                low = middle + 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
        int i = binarySearch(arr, 6);
        System.out.println("i = " + i);
    }
}
